package com.cc.shiro.realms;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.cc.daos.UserMapper;
import com.cc.models.Power;
import com.cc.models.Role;
import com.cc.models.User;

public class MyRealm extends AuthorizingRealm {

	@Autowired
	private UserMapper userMapper;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		String username = (String)arg0.getPrimaryPrincipal();
		User user = new User();
		user.setUserName(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		List<Role> roles = userMapper.queryRoleByUser(user);
		for (Role role : roles) {
			info.addRole(role.getRoleName());
		}
		List<Power> permissions = userMapper.queryPowerByUser(user);
		for (Power power : permissions) {
			info.addStringPermission(power.getPowerExp());
		}
		return info;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		String username = token.getUsername();
		Map params = new HashMap();
		params.put("userName", username);
		List<User> list = userMapper.findUserByParam(params);
		if(list!=null && list.size()>0){
			User user = list.get(0);
			if(user.getUserPassword().equals(new String(token.getPassword()))){
				AuthenticationInfo authInfo = new SimpleAuthenticationInfo(user.getUserName(),user.getUserPassword(),this.getName());
				setSession("USER",user);
				setSession("userId", user.getUserId());
				return authInfo;
			}
		}
		return null;
	}

	private void setSession(Object key, Object value) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
			if (null != session) {
				session.setAttribute(key, value);
			}
		}
	}
}
